package communication;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.ArrayList;
import java.util.Set;
import java.util.TreeMap;

import org.jgroups.Address;
import org.jgroups.util.Rsp;
import org.jgroups.util.RspList;

public class GroupResponse {
	
	private RspList rspList;
	
	GroupResponse(RspList rspList) {
		this.rspList = rspList;
	}
	
	public Map<Address, Response> getResponseMap() {
		Map<Address, Response> responses = new TreeMap<Address, Response>();
		
		Set<Entry<Address, Rsp>> entries = rspList.entrySet();
		for(Entry<Address, Rsp> entry : entries) {
			if (entry.getValue() instanceof ParameterizedMessage) {
				responses.put(entry.getKey(), new Response(entry.getValue()));
			} else {
				responses.put(entry.getKey(),
						new Response((Rsp<ParameterizedMessage>) CommunicationHelper.buildErrorMsg(entry.getValue())));
			}
		}
		
		
		return responses;
	}
	
	@SuppressWarnings("rawtypes")
	public List<Response> getResponses() {
		List<Response> responses = new ArrayList<Response>();
		
		for(Rsp rsp : rspList.values()) {
			if (!(rsp.getValue() instanceof ParameterizedMessage)) {
				rsp.setValue(CommunicationHelper.buildErrorMsg(rsp.getValue()));
			}
			Response response = new Response(rsp);
			String result = response.getMessage().getParameter("result");
			if (result != null && result.equals("ignored"))
				continue;
			responses.add(response);
		}
		
		return responses;
	}
	
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append(this.getResponseMap().toString());
		
		return sb.toString();
	}

}
